# -*- coding: utf-8 -*-
"""
.. todo:: initial pyknic doc
.. todo:: explain how logging works and is configured

"""

class VersionMissmatchError(Exception):
    pass

# check python version
import sys


def check_version(upper_version, actual_version, lower_version):
    if not upper_version > actual_version >= lower_version:
        raise VersionMissmatchError("expected version: {0} > {1} >= {2}!".format(upper_version, actual_version, lower_version))

check_version((3, 3), tuple(sys.version_info), (2, 6))
    
# -----------------------------------------------------------------------------


# -----------------------------------------------------------------------------
import os
import logging
import logging.handlers # pylint: disable=W0404
import atexit

# local imports
from . import _settings
settings = _settings.settings
# from _settings import settings # pylint: disable=W0403
from . import info # pylint: disable=W0404

# -----------------------------------------------------------------------------
# shut down logging properly
atexit.register(logging.shutdown)
# -----------------------------------------------------------------------------
class NullHandler(logging.Handler):
    """
    A logging handler that does nothing.
    """
    def emit(self, record):
        """Does nothing"""
        pass
# -----------------------------------------------------------------------------
def _set_up_logging():
    """
    Sets up a basic logging configuration.
    """
    logger = logging.getLogger("pyknic")
    if not settings['log_to_file'] and not settings['log_to_console']:
        # setting up logging as suggested by the help
        # not sure why it does still log to console
        # is this suppressing the message:
        # “No handlers could be found for logger pyknic”
        null_handler = NullHandler()
        logger.addHandler(null_handler)
        
    # if logging.getLogger().level != settings['log_level']:
        # settings['log_level'] = logging.getLogger().level
    # if logging.getLogger().level >= settings['log_level']:
        # logging.getLogger().setLevel(settings['log_level'])
        # print '??', 'setting log level', settings['log_level']

    _formatter = logging.Formatter(settings['log_format'])
    if settings['log_to_file']: # and settings['log_file_handler'] is None:
        log_filename = os.path.join(_settings.settings['log_path'], 
                                    _settings.settings['log_filename'])
        _handler = logging.handlers.RotatingFileHandler( log_filename, \
                                            maxBytes=1024 * 1024, backupCount=5)
        _handler.setFormatter(_formatter)
        _handler.setLevel(settings['log_level'])
        logger.addHandler(_handler)
        settings['log_file_handler'] = _handler

    if settings['log_to_console']: # and settings['log_console_handler'] is None:
        console_handler = logging.StreamHandler()
        console_handler.setLevel(settings['log_level'])
        console_handler.setFormatter(_formatter)
        logger.addHandler(console_handler)
        settings['log_console_handler'] = console_handler

# -----------------------------------------------------------------------------

# read only
is_initialized = False
default_options = [] # "default values should go here"

def init(options=default_options):
    """
    Call this to initialize pyknic after you have changed its settings.
    After calling this method changes in settings may not have effect 
    (depends on the setting).
    
    .. todo:: explain logging options (maybe in settings?) and how it works
    .. todo:: replace settings with options using optparse!!
    """
    global is_initialized # pylint: disable=W0603
    if not is_initialized:
        __all__ = ["context", "cache", "events", "timing", "info", "mathematics"]
        is_initialized = True
        _set_up_logging()
        
        # from . import _debug # pylint: disable=W0404
        
        log = logging.getLogger('pyknic')

        # mark the start in the log
        log.info("**************************************************")
        log.info("%-50s" % ("pyknic v" + info.version + " (c) DR0ID 2011"))
        log.info("**************************************************")
        log.info("using python version: " + sys.version)

        log.info("settings at start up:")
        for key in settings.keys():
            log.info("  %-20s: %s" % (str(key), str(settings[key])))

        # other modules
        from . import context # pylint: disable=W0404, W0612
        from . import cache # pylint: disable=W0404, W0612
        from . import events # pylint: disable=W0404, W0612
        from . import timing # pylint: disable=W0404, W0612
        from . import mathematics # pylint: disable=W0404, W0612
    else:
        logging.warn("pyknic already initialized, should only called once")


# -----------------------------------------------------------------------------

